package com.lib.image.preview

import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lib.image.ImageLoader.loadFitCenterImage
import com.lib.image.LiveBusEvent
import com.lib.image.R
import com.lib.image.databinding.FragmentPhotoEditorBinding
import com.lib.image.ex.showToast
import com.lib.image.until.FileUtil

class PhotoEditorFragment : Fragment(), View.OnClickListener {

    private lateinit var mViewModel: PhotoEditorViewModel
    private lateinit var mViewBinding: FragmentPhotoEditorBinding

    private var mRotate = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = ViewModelProvider(requireActivity()).get(PhotoEditorViewModel::class.java)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mViewBinding = FragmentPhotoEditorBinding.inflate(inflater, container, false)
        return mViewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewBinding.run {
            //不支持,如果使用kotlin低于1.4.21版本，会报错，原因目前不知道，只是存在kotlin文件中，java并不会出现这个问题
//            btnBack.setOnClickListener(::onViewClick)
            btnBack.setOnClickListener(this@PhotoEditorFragment)
            btnRotate.setOnClickListener(this@PhotoEditorFragment)
            btnClip.setOnClickListener(this@PhotoEditorFragment)
            btnOperate.setOnClickListener(this@PhotoEditorFragment)
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mViewModel.getImagePath().observe(viewLifecycleOwner, Observer {
            loadFitCenterImage(mViewBinding.photoView, it, fragment = this)
        })
    }

    /**
     * 裁剪
     */
    private fun jump2ClipPage() {
        val bundle = Bundle().apply {
            putString("imagePath", mViewModel.getImagePath().value)
        }
        Navigation.findNavController(requireView()).navigate(
            R.id.fragment_photo_clip,
            PhotoClipFragmentArgs.fromBundle(bundle).toBundle()
        )
    }

    private fun saveBitmap2Disk() {
        if (mViewBinding.photoView.drawable == null) {

            return
        }
        activity?.let {
            //旋转了度数才进行裁剪，生成新的图片
            if(getRotate() > 0) {
                val bitmap = (mViewBinding.photoView.drawable as BitmapDrawable).bitmap
                val file = FileUtil.createImageFile(it.applicationContext, "clip_${System.currentTimeMillis()}.jpg")
                FileUtil.saveBitmap(it.applicationContext, bitmap, file, 100)
                if (file.length() <= 0) {
                    showToast("图片保存失败！！")
                    return
                }
                LiveEventBus.get(LiveBusEvent.EVENT_OPERATED, String::class.java)
                    .post(file.absolutePath)
                return@let
            }
            //如果没进行旋转操作，使用原图
            LiveEventBus.get(LiveBusEvent.EVENT_OPERATED, String::class.java)
                .post(mViewModel.getImagePath().value)
        }
    }

    private fun rotateBitmap() {
        if (mViewBinding.photoView.drawable == null) {
            return
        }
        val bitmap = (mViewBinding.photoView.drawable as BitmapDrawable).bitmap
        val matrix = Matrix()
        matrix.setRotate(90f)
        val newBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
        mViewBinding.photoView.setImageBitmap(newBitmap)
        mRotate += 90
        if (mRotate >= 360) {
            mRotate = 0
        }
        //不要手动释放，使用glide了。glide会自己释放
//        bitmap.recycle()
    }

    private fun getRotate(): Int {
        return mRotate
    }

    override fun onClick(v: View) {
        mViewBinding.run {
            when (v) {
                btnBack -> requireActivity().finish()
                btnRotate -> rotateBitmap()
                btnOperate -> saveBitmap2Disk()
                btnClip -> jump2ClipPage()
            }
        }
    }
}